<template>
    <page-container title="订单交易流水" :showBack="true">
        <template v-slot:nav-left>
            <view class="nav-left" @click="goBack">
                <uni-icons type="left" size="20" color="#d4af37"></uni-icons>
            </view>
        </template>
        <view class="flow-list-page">
            <!-- 订单信息卡片 -->
            <view class="order-card" v-if="orderInfo">
                <!-- 订单基本信息 -->
                <view class="order-info">
                    订单基本信息
                </view>
                <view class="order-header">
                    <text class="order-no">订单号：{{ orderInfo.orderNo || '--' }}</text>
                    <text class="order-status" :class="orderInfo.statusClass">
                        {{ orderInfo.statusText }}
                    </text>
                </view>

                <view class="order-details">
                    <view class="detail-item">
                        <text class="label">客户姓名：</text>
                        <text class="value">{{ orderInfo.cusName || '--' }}</text>
                    </view>
                    <view class="detail-item">
                        <text class="label">物料类型：</text>
                        <text class="value">{{ materialTypeOptions[orderInfo.materialType] || '--' }}</text>
                    </view>
                    <view class="detail-item">
                        <text class="label">订单类型：</text>
                        <text class="value">{{ orderInfo.orderType === 'BUY' ? '买料' : '卖料' }}</text>
                    </view>
                    <view class="detail-item">
                        <text class="label">克重：</text>
                        <text class="value">{{ orderInfo.weight || '--' }}g</text>
                    </view>
                    <view class="detail-item">
                        <text class="label">下单单价：</text>
                        <text class="value">￥{{ orderInfo.orderPrice || '--' }}</text>
                    </view>
                    <view class="detail-item">
                        <text class="label">定金：</text>
                        <text class="value">￥{{ formatPrice(orderInfo.retainerAmount) || '--' }}</text>
                    </view>

                    <view class="detail-item">
                        <text class="label">定金初始金额：</text>
                        <text class="value">￥{{ formatPrice(orderInfo.retainerAmount) || '--' }}</text>
                    </view>
                    <view class="detail-item">
                        <text class="label">定金余额：</text>
                        <text class="value">￥{{ formatPrice(orderInfo.retainerAmountBalance) || '--' }}</text>
                    </view>
                    <view class="detail-item">
                        <text class="label">当前仓管费：</text>
                        <text class="value">{{ orderInfo.manageFee || '--' }}</text>
                    </view>
                    <view class="detail-item">
                        <text class="label">止盈单价：</text>
                        <text class="value">{{ orderInfo.stopProfitLimit || '--' }}</text>
                    </view>
                    <view class="detail-item">
                        <text class="label">止损单价：</text>
                        <text class="value">{{ orderInfo.stopLossLimit || '--' }}</text>
                    </view>
                    <view class="detail-item">
                        <text class="label">下单时间：</text>
                        <text class="value">{{ orderInfo.orderTime || '--' }}</text>
                    </view>
                </view>
            </view>

            <!-- 筛选栏 -->
            <view class="filter-bar" v-if="false">
                <view class="filter-item">
                    <text class="filter-label">交易类型：</text>
                    <picker @change="onTradeTypeChange" :value="tradeTypeIndex" :range="tradeTypeOptions">
                        <text class="filter-value">{{ tradeTypeOptions[tradeTypeIndex] }} ▼</text>
                    </picker>
                </view>
                <view class="filter-item">
                    <text class="filter-label">交易状态：</text>
                    <picker @change="onTradeStatusChange" :value="tradeStatusIndex" :range="tradeStatusOptions">
                        <text class="filter-value">{{ tradeStatusOptions[tradeStatusIndex] }} ▼</text>
                    </picker>
                </view>
            </view>

            <!-- 交易流水列表 -->
            <scroll-view class="flow-list" scroll-y @scrolltolower="loadMore" @refresherrefresh="onRefresh"
                :refresher-enabled="true" :refresher-triggered="refreshing" :style="{ height: 'calc(100vh - 300rpx)' }">
                <view class="flow-item" v-for="(item, index) in flowList" :key="index">
                    <view class="flow-header">
                        <text class="flow-time">{{ formatTime(item.tradeTime) }}</text>
                    </view>

                    <view class="flow-content">
                        <view class="flow-row">
                            <text class="flow-label">交易类型：</text>
                            <text class="flow-value">{{ getTradeTypeText(item.tradeType) }}</text>
                        </view>
                        <view class="flow-row">
                            <text class="flow-label">交易价格：</text>
                            <text class="flow-value price">￥{{ formatPrice(item.tradePrice) }}</text>
                        </view>
                        <view class="flow-row">
                            <text class="flow-label">交易克重：</text>
                            <text class="flow-value">{{ formatWeight(item.tradeWeight) }}g</text>
                        </view>
                        <view class="flow-row">
                            <text class="flow-label">交易金额：</text>
                            <text class="flow-value amount">￥{{ formatPrice(item.tradeAmount) }}</text>
                        </view>
                        <view class="flow-row" v-if="item.remarks">
                            <text class="flow-label">备注：</text>
                            <text class="flow-value remarks">{{ item.remarks }}</text>
                        </view>
                    </view>
                </view>

                <!-- 加载更多提示 -->
                <view class="load-more">
                    <view v-if="loading" class="loading">
                        <text class="loading-text">加载中...</text>
                        <view class="loading-dots">
                            <view class="dot"></view>
                            <view class="dot"></view>
                            <view class="dot"></view>
                        </view>
                    </view>
                    <text v-else-if="noMore && flowList.length > 0" class="no-more">没有更多数据了</text>
                    <text v-else-if="flowList.length === 0" class="empty">暂无交易流水数据</text>
                </view>
            </scroll-view>
        </view>
    </page-container>
</template>

<script>
export default {
    data() {
        return {
            orderId: '', // 订单ID
            orderInfo: null, // 订单信息

            // 筛选选项
            tradeTypeIndex: 0,
            tradeTypeOptions: ['全部', '买料', '卖料'],

            tradeStatusIndex: 0,
            tradeStatusOptions: ['全部', '待确认', '已确认', '已完成', '已取消'],

            // 交易流水数据
            flowList: [],
            page: 1,
            pageSize: 20,
            loading: false,
            noMore: false,
            refreshing: false,

            // 防抖定时器
            loadMoreTimer: null,
            materialTypeOptions: {
                'GOLD': '黄金',
                'SILVER': '白银',
                'PLATINUM': '铂金',
                'PALLADIUM': '钯金',
            },
        }
    },

    onLoad(options) {
        if (options.id) {
            this.orderId = options.id;
            this.getOrderInfo();
            this.loadFlowList();
        }
    },

    onUnload() {
        // 清理定时器
        if (this.loadMoreTimer) {
            clearTimeout(this.loadMoreTimer);
            this.loadMoreTimer = null;
        }
    },

    methods: {
        goBack() {
            setTimeout(() => {
                uni.navigateBack()
            }, 100)
        },
        // 获取订单信息
        async getOrderInfo() {
            // /applet/customer/orders/info/{orderId}
            const res = await this.$http.get(`/applet/customer/orders/info/${this.orderId}`);
            this.orderInfo = res.data;

            // 预计算状态样式类和文本
            if (this.orderInfo && this.orderInfo.orderStatus) {
                this.orderInfo.statusClass = this.getStatusClass(this.orderInfo.orderStatus);
                this.orderInfo.statusText = this.getStatusText(this.orderInfo.orderStatus);
            }
        },

        // 加载交易流水列表
        async loadFlowList() {
            if (this.loading || this.noMore) return;
            this.loading = true;

            try {
                let params = {
                    size: this.pageSize,
                    current: this.page,
                    orderId: this.orderId
                }

                // 添加筛选条件
                if (this.tradeTypeIndex > 0) {
                    params.tradeType = this.tradeTypeOptions[this.tradeTypeIndex];
                }
                if (this.tradeStatusIndex > 0) {
                    params.tradeStatus = this.tradeStatusOptions[this.tradeStatusIndex];
                }
                const res = await this.$http.post('/applet/customer/orders/tradeLog/list', params);
                const newFlows = res.data.records || [];

                // 如果是第一页，直接替换数据
                if (this.page === 1) {
                    this.flowList = newFlows;
                } else {
                    // 如果不是第一页，累加数据
                    this.flowList = [...this.flowList, ...newFlows];
                }

                // 判断是否还有更多数据
                if (newFlows.length < this.pageSize) {
                    this.noMore = true;
                }

                this.page++;
            } catch (error) {
                uni.showToast({
                    title: error.msg || '加载失败',
                    icon: 'none'
                });

                // 如果是第一页加载失败，显示空状态
                if (this.page === 1) {
                    this.flowList = [];
                }
            } finally {
                this.loading = false;
            }
        },

        // 触底加载更多
        loadMore() {
            // 清除之前的定时器
            if (this.loadMoreTimer) {
                clearTimeout(this.loadMoreTimer);
            }

            // 防抖处理，避免频繁触发
            this.loadMoreTimer = setTimeout(() => {
                if (!this.loading && !this.noMore) {
                    this.loadFlowList();
                }
            }, 100);
        },

        // 下拉刷新
        async onRefresh() {
            this.refreshing = true;
            this.page = 1;
            this.noMore = false;
            this.flowList = [];
            await this.loadFlowList();
            this.refreshing = false;
        },

        // 筛选条件变化
        onTradeTypeChange(e) {
            this.tradeTypeIndex = e.detail.value;
            this.refreshList();
        },

        onTradeStatusChange(e) {
            this.tradeStatusIndex = e.detail.value;
            this.refreshList();
        },

        // 刷新列表
        refreshList() {
            this.page = 1;
            this.noMore = false;
            this.flowList = [];
            this.loadFlowList();
        },

        // 获取订单状态样式类
        getStatusClass(status) {
            const statusMap = {
                'WAIT_PAY': 'warning',
                'PENDING': 'warning',
                'WAIT_SHIPMENT': 'warning',
                'COMPLETED': 'success',
                'CANCELLED': 'success',
                'PARTIALLY_FILLED': 'warning',
                'FILLED': 'success',
            };
            return statusMap[status] || 'default';
        },

        // 获取订单状态文本
        getStatusText(status) {
            const statusMap = {
                'WAIT_PAY': '待支付',
                'PENDING': '已定价',
                'WAIT_SHIPMENT': '待发货',
                'COMPLETED': '已结算',
                'CANCELLED': '已结算',
                'PARTIALLY_FILLED': '部分成交',
                'FILLED': '已成交',
            };
            return statusMap[status] || '未知状态';
        },

        // 获取交易状态样式类
        getTradeStatusClass(status) {
            const statusMap = {
                'PENDING': 'warning',
                'CONFIRMED': 'info',
                'COMPLETED': 'success',
                'CANCELLED': 'error',
            };
            return statusMap[status] || 'default';
        },

        // 获取交易状态文本
        getTradeStatusText(status) {
            const statusMap = {
                'PENDING': '待确认',
                'CONFIRMED': '已确认',
                'COMPLETED': '已完成',
                'CANCELLED': '已取消',
            };
            return statusMap[status] || '未知状态';
        },

        // 获取交易类型文本
        getTradeTypeText(type) {
            const typeMap = {
                // 'BUY': '买料',
                // 'SELL': '卖料',
                'ORDER': '下单',
                'ADD_RETAINER': '补充定金',
                'CANCELLED': '违约结算',
                'COMPLETED': '交付结算',
            };
            return typeMap[type] || '未知类型';
        },

        // 格式化时间
        formatTime(time) {
            if (!time) return '--';
            return time;
        },

        // 格式化价格
        formatPrice(price) {
            if (!price || price === 0) return '0.00';
            const num = parseFloat(price);
            return num.toLocaleString('zh-CN', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            });
        },

        // 格式化克重
        formatWeight(weight) {
            if (!weight || weight === 0) return '0.00';
            return parseFloat(weight).toFixed(2);
        }
    }
}
</script>

<style scoped lang="scss">
@import '@/uni.scss';

.flow-list-page {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background-color: #F5F5F6;
    padding-top: 20rpx;
}

.page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 88rpx;
    padding: 0 30rpx;
    background-color: #fff;
    border-bottom: 1rpx solid #eee;
}

.header-left {
    display: flex;
    align-items: center;
    font-size: 28rpx;
    color: #333;
}

.back-icon {
    font-size: 36rpx;
    margin-right: 10rpx;
}

.header-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
}

.header-right {
    width: 100rpx;
}

.order-card {
    padding: 20rpx 26rpx;
    background-color: #fff;
    // box-shadow: 0 0 10rpx 0 rgba(0, 0, 0, 0.1);
}

.order-info {
    padding-bottom: 20rpx;
    border-bottom: 1rpx solid #eee;
    margin-bottom: 20rpx;
    font-size: 32rpx;
    color: #000;
    font-weight: bold;
}

.order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    margin-bottom: 20rpx;
}

.order-no {
    font-size: 28rpx;
    color: #0B1F20;
    font-weight: bold;
}

.order-status {
    font-size: 24rpx;
    padding: 8rpx 16rpx;
    border-radius: 10rpx;
}

.order-status.warning {
    color: #fff;
    background-color: #FF9500;
}

.order-status.success {
    color: #fff;
    background-color: #4CD964;
}

.order-status.error {
    color: #fff;
    background-color: #FF3B30;
}

.order-status.default {
    color: #666;
    background-color: #f0f0f0;
}

.order-details {
    display: flex;
    flex-direction: column;
    gap: 15rpx;
}

.detail-item {
    display: flex;
    align-items: center;
}

.label {
    font-size: 28rpx;
    color: #0B1F20;
    width: 200rpx;
}

.value {
    font-size: 26rpx;
    color: #666;
    font-weight: 500;
}

.filter-bar {
    display: flex;
    justify-content: space-around;
    padding: 20rpx 26rpx;
    background-color: #fff;
}

.filter-item {
    display: flex;
    align-items: center;
}

.filter-label {
    font-size: 26rpx;
    color: #666;
    margin-right: 10rpx;
}

.filter-value {
    font-size: 26rpx;
    color: #333;
    padding: 8rpx 16rpx;
    background-color: #f5f5f5;
    border-radius: 16rpx;
}

.flow-list {
    flex: 1;
    overflow: hidden;
    margin-top: 20rpx;
}

.flow-item {
    margin: 0 20rpx 20rpx;
    background-color: #fff;
    border-radius: 16rpx;
    overflow: hidden;
}

.flow-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 30rpx;
    background-color: #f8f9fa;
    border-bottom: 1rpx solid #eee;
}

.flow-time {
    font-size: 24rpx;
    color: #666;
}

.flow-status {
    font-size: 22rpx;
    padding: 6rpx 12rpx;
    border-radius: 10rpx;
}

.flow-status.warning {
    color: #fff;
    background-color: #FF9500;
}

.flow-status.info {
    color: #fff;
    background-color: #007AFF;
}

.flow-status.success {
    color: #fff;
    background-color: #4CD964;
}

.flow-status.error {
    color: #fff;
    background-color: #FF3B30;
}

.flow-status.default {
    color: #666;
    background-color: #f0f0f0;
}

.flow-content {
    padding: 30rpx;
}

.flow-row {
    display: flex;
    align-items: center;
    margin-bottom: 15rpx;
}

.flow-row:last-child {
    margin-bottom: 0;
}

.flow-label {
    font-size: 26rpx;
    color: #666;
    width: 140rpx;
}

.flow-value {
    font-size: 26rpx;
    color: #333;
    flex: 1;
}

.flow-value.price,
.flow-value.amount {
    color: #FF6B35;
    font-weight: 600;
}

.flow-value.remarks {
    color: #999;
    // font-style: italic;
}

.load-more {
    text-align: center;
    padding: 30rpx;
    font-size: 24rpx;
    color: #999;
}

.loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

.loading-text {
    margin-bottom: 15rpx;
}

.loading-dots {
    display: flex;
    align-items: center;
    justify-content: center;
}

.dot {
    width: 8rpx;
    height: 8rpx;
    border-radius: 50%;
    background-color: #999;
    margin: 0 4rpx;
    animation: loading 1.4s infinite ease-in-out both;
}

.dot:nth-child(1) {
    animation-delay: -0.32s;
}

.dot:nth-child(2) {
    animation-delay: -0.16s;
}

@keyframes loading {

    0%,
    80%,
    100% {
        transform: scale(0);
        opacity: 0.5;
    }

    40% {
        transform: scale(1);
        opacity: 1;
    }
}

.no-more {
    color: #999;
}

.empty {
    color: #ccc;
    font-size: 26rpx;
}
</style>
